package org.gurms.web.filter;

import java.lang.reflect.Method;
import java.util.Map;

import org.gurms.common.config.GlobalConfig;
import org.gurms.common.config.GlobalMessage;
import org.gurms.common.exception.GurmsServiceException;
import org.gurms.common.util.CommonUtil;
import org.gurms.common.util.SpringUtil;
import org.gurms.common.validate.GurmsValid;
import org.gurms.common.validate.Validation;
import org.gurms.web.action.BaseAction;
import org.gurms.web.action.CRUDActionSupport;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class GurmsInterceptor implements Interceptor {

	private String[] ignoreMethod;
	private String[] ignoreAction;
	
	public void destroy() {
		ignoreMethod = null;
	}

	public void init() {
		ignoreMethod = GlobalConfig.INTERCEPTOR_IGNORE_METHOD.split(",");
		ignoreAction = GlobalConfig.INTERCEPTOR_IGNORE_ACTION.split(",");
	}

	public String intercept(ActionInvocation actioninvocation) throws Exception {
		Object action = actioninvocation.getAction();
		String actionName = action.getClass().getSimpleName();
		String methodName = actioninvocation.getProxy().getMethod();
		//不在过滤action/method列表中的要效验session
		if(!CommonUtil.existHead(actionName,ignoreAction) && !CommonUtil.existHead(methodName,ignoreMethod)){
			Map session = actioninvocation.getInvocationContext().getSession();
			Object user = session.get(BaseAction.S_KEY_USER);
			if(user == null){
				throw new GurmsServiceException(GlobalMessage.getMessage("9100"));
			}
		}		
		
		//后台数据的效验和前台表单效验脚本的生成
		if(CRUDActionSupport.class.isInstance(action)){
			Method method = action.getClass().getMethod(methodName);
			if(method.isAnnotationPresent(GurmsValid.class)){
				GurmsValid valid = method.getAnnotation(GurmsValid.class);
				
				String clzName = valid.type().getName();
				String[] props = valid.props();
				
				Validation gv = SpringUtil.getBean("gurmsValidator");
				String script = gv.script(clzName, props);
				System.out.println("client : " + script);

				((CRUDActionSupport)action).setScript(script);
			}
		}
		
		return actioninvocation.invoke();
	}
}
